/*
 * @Author: 非幡动 438484791@qq.com
 * @Date: 2024-06-27 18:40:30
 * @LastEditors: 非幡动 438484791@qq.com
 * @LastEditTime: 2024-07-23 09:24:44
 * @FilePath: \react-cornerstone-3d\src\views\StackImages-wado.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {useEffect, useRef} from "react";
import {Enums, init as csRenderInit, RenderingEngine, imageLoader, metaData} from "@cornerstonejs/core";
import initCornerstoneDICOMImageLoader from '../utils/initCornerstoneDICOMImageLoaderT.js';
import initDemo from '../utils/initDemo.js';
import axios from "axios";
import registerWebImageLoader from "../utils/registerWebImageLoader.js";
import hardcodedMetaDataProvider from '../utils/hardcodedMetaDataProvider.js';

const {ViewportType} = Enums;

const renderingEngineId = 'myRenderingEngine';
const viewportId = 'CT_STACK';

const windowWidth = 400;
const windowCenter = 40;

const lower = windowCenter - windowWidth / 2.0;
const upper = windowCenter + windowWidth / 2.0;

const ctVoiRange = {lower, upper};

/**
 * wodo uri的方式
 */
function StackImages() {

    let viewport;
    let instanceUIDref = useRef([]);
    let imageIdref = useRef([]);

    useEffect(() => {
        const content = document.getElementById('content');
        if (!content.children || (content.children.length === 0)) {
            setup();
        }
    }, [])

    const setup = async () => {
        const content = document.getElementById('content');
        const element = document.createElement('div');
        element.id = 'cornerstone-element';
        element.style.width = '50%';
        element.style.height = '100%';
        content.appendChild(element);

        initCornerstoneDICOMImageLoader();
        await csRenderInit({
            gpuTier: {
                tier: 0
            }
        });
        // await initDemo();

        metaData.addProvider(
            // @ts-ignore
            (type, imageId) => hardcodedMetaDataProvider(type, imageId, imageIds),
            10000
          );

        const renderingEngine = new RenderingEngine(renderingEngineId);

        const viewportInput = {
            viewportId,
            type: ViewportType.STACK,
            element
        };

        renderingEngine.enableElement(viewportInput);

        viewport = (
            renderingEngine.getViewport(viewportId)
        );
        // const stack = [`wadouri:http://10.16.100.58/api/studies/1.2.156.112605.189250941700568.240411083139.2.9628.13045/series/1.2.156.112605.189250941700568.240411083146.3.6096.46376/instances/1.2.156.112605.189250941700568.240411083231.4.18284.73325/wodo`];
        // let response = await request({url: '/wado', 
        // method: 'GET',
        // param: {
        //     Level: 'study',
        //     Query: { AccessionNumber: accessionNumber }
        // }});
        // StudyInstanceUID: 1.2.840.113619.186.808617090127.20210303084422103.763
        // SeriesInstanceUID: 1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313
        const requestType = 'WADO';
        let accessionNumber = '10210303186008';
        let studyUID = '1.2.840.113619.186.808617090127.20210303084422103.763';
        let seriesUID = '1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313';
        const objectUID = '1.3.12.2.1107.5.1.4.74466.30000021030207060846400168719';
        const orthancURL = '/server'
        const username = '';  // Orthanc 用户名
        const password = '';  // Orthanc 密码
        // const url = `http://localhost:8042/api/wado?requestType=WADO&StudyInstanceUID=${studyUID}&SeriesInstanceUID=${seriesUID}`;
        // http://39.105.150.149:8042/wado?requestType=WADO&studyUID=1.2.840.113619.186.808617090127.20210303084422103.763&seriesUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313&objectUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168719&contentType=image/jpeg
        // const url = `/wado?requestType=WADO&studyUID=${studyUID}&seriesUID=${seriesUID}&objectUID=${objectUID}&contentType=image/jpeg`;
        
        let url = orthancURL + '/tools/find'
        let response = await axios.post(url,
            {
            "Level": "Study",
            "Query": {
                AccessionNumber:  accessionNumber
            }
            },
            {
                headers: {"Content-Type": "application/json"},
                auth: {
                    username: username,
                    password: password
                  }
            }
        );
        console.log('response', response.data);

        url = orthancURL + `/dicom-web/studies/?AccessionNumber=${accessionNumber}`;
        await axios(url).then((res) => {
            console.log('url', res);
            const study = res.data[0];
            // 获取Study Instance UID
            studyUID = study['0020000D'].Value[0];
            const dicomUrl = study['00081190'].Value[0];
            const baseapiUrl = dicomUrl.replace(/^(http:\/\/[^\/]+)\/dicom-web/, '/server/dicom-web');
            console.log(study, studyUID, baseapiUrl);
        })

        let seriesURL = orthancURL + `/dicom-web/studies/${studyUID}/series`
        await axios.get(seriesURL, {
            headers: {
              'Accept': 'application/json'
            }
          })
            .then((res) => {
                console.log("series", res.data);
                let series = res.data[0];
                seriesUID = series['0020000E'].Value[0];
                fetchInstances(studyUID, seriesUID);
            })
        // console.log(stack);
        // const stack = ['http://39.105.150.149:8001/11716580'];
        // axios('http://localhost:3000/server/wado?requestType=WADO&studyUID=1.2.840.113619.186.808617090127.20210303084422103.763&seriesUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313&objectUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168708&contentType=image/jpeg').then((res) => {
        //     imageIdref.current.push(res.data);
        // })
        const imageIds = ['web:/server/wado?requestType=WADO&studyUID=1.2.840.113619.186.808617090127.20210303084422103.763&seriesUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313&objectUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168644&contentType=application/dicom', 'web:/server/wado?requestType=WADO&studyUID=1.2.840.113619.186.808617090127.20210303084422103.763&seriesUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313&objectUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168475&contentType=application/dicom']
        imageIdref.current.push('web:http://39.105.150.149:8042/wado?requestType=WADO&studyUID=1.2.840.113619.186.808617090127.20210303084422103.763&seriesUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313&objectUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168644&contentType=image/jpeg');
        imageIdref.current.push('web:http://39.105.150.149:8042/wado?requestType=WADO&studyUID=1.2.840.113619.186.808617090127.20210303084422103.763&seriesUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168313&objectUID=1.3.12.2.1107.5.1.4.74466.30000021030207060846400168475&contentType=image/jpeg');
        registerWebImageLoader(imageLoader);
        
        console.log(imageIdref.current)
        
        
        // await viewport.setStack(imageIds);
        // viewport.setProperties({voiRange: ctVoiRange});
        // viewport.render();
        // // render volume viewports
        // renderingEngine.render();
    }

    // 定义fetchInstances函数
    async function fetchInstances(studyUID, seriesUID) {
    // 构建WADO URL
    const instancesUrl = `/server/dicom-web/studies/${studyUID}/series/${seriesUID}/instances`;
  
    // 发送GET请求获取Instances列表
    await axios.get(instancesUrl, {
      headers: {
        'Accept': 'application/json'
      }
    })
      .then(async response => {
        if (response.data.length === 0) {
          console.error(`No instances found for the series ${seriesUID}`);
          return;
        }
        // 提取每个Instance的Instance UID
        const instancesList = response.data;
        // 创建一个Promise数组来处理所有的异步操作
        const promises =  instancesList.forEach(async instance => {
          const instanceUID = instance['00080018'].Value[0];
          let imageURL = `/server/wado?requestType=WADO&studyUID=${studyUID}&seriesUID=${seriesUID}&objectUID=${instanceUID}&contentType=image/jpeg`;
          await axios(imageURL).then((res) => {
            let image = res.data
            imageIdref.current.push(image);
          });
          instanceUIDref.current.push(instanceUID);
          
        });
        // 等待所有的Promise完成
        await Promise.all(promises);
        // 打印所有Instance UID
        console.log('All Instance UIDs:', instanceUIDref.current);
        console.log('All imageIdref UIDs:', imageIdref.current);
      })
      .catch(error => {
        console.error('Error fetching instances information:', error.response ? error.response.data : error.message);
      });
  }

    const getInfo = () => {
    }

    const drawPoint = () => {
        const context = viewport.canvas.getContext('2d');
        context.fillStyle = 'rgba(203,195,145,0.5)';
        context.fillRect(0, 0, 10, 10)
    }

    return (
        <div style={{width: '100%', height: '400px'}}>
            <div>
                <button onClick={getInfo}>get info</button>
                <button onClick={drawPoint}>draw</button>
            </div>
            <div id="content" style={{width: '100%', height: '100%'}}/>
        </div>

    );
}

export default StackImages;
